package com.fsc.fragment.flag;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.fsc.fragment.DBHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class FlagDao {
	
	//获取系统当前时间
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	String date = dateFormat.format(new java.util.Date());
	private DBHelper dbHelper;
	
	//重写构造方法
	public FlagDao(Context context){
		dbHelper = new DBHelper(context);
	}
	//新增便签
	public void insertFlag(Flag flag){
		//得到连接
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		//调用方法
		ContentValues values = new ContentValues();
		values.put("flag", flag.getFlag());
		values.put("time",flag.getTime());
		long id = database.insert("Flag", null, values);

		Log.i("TAG", "insertCount="+id);
		flag.setId((int) id);
		flag.setTime(date);
		//关闭连接
		database.close();
	}
	
	//查询便签
	public List<Flag> queryFlag(){
		List<Flag> list = new ArrayList<Flag>();
		
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		Cursor cursor = database.query("Flag", null, null, null, null, null, "_id desc");
		
		while(cursor.moveToNext()){
			int id = cursor.getInt(0);
			String flag = cursor.getString(1);
			String time = cursor.getString(2);
			list.add(new Flag(id,flag,time));
		}
		cursor.close();
		database.close();
		
		return list;
	}
	
	public List<Flag> queryById(int id){
		List<Flag> list = new ArrayList<Flag>();
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		Cursor cursor = database.query("Flag", null, "_id=?", new String[]{id+""}, null, null, null);
				
		while (cursor.moveToNext()){
			
			int _id=cursor.getInt(0);
			String flag = cursor.getString(1);
			String time = cursor.getString(2);
			
			list.add(new Flag(_id,flag,time));
		}
		cursor.close();
		database.close();
		return list;
	}
	//更新便签
	public void updateFlag(Flag flag){
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("flag", flag.getFlag());
		values.put("time", flag.getTime());
		int updateCount = database.update("Flag", values , "_id=" + flag.getId(),null);
		Log.i("TAG", "updateCount="+updateCount);
		
		flag.setTime(date);
		database.close();
	}
	
	//删除便签
	public void deleteFlag(int id){
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		int deleteCount = database.delete("Flag", "_id=?", new String[]{id+""});
		Log.i("TAG", "deleteCount="+deleteCount);
		
		database.close();
	}
}
